// 主进程创建控制端主窗体

const { BrowserWindow } = require("electron");
// 检查 electron 是否运行在开发环境
const isDev = require("electron-is-dev");
const path = require("path");

let win = null;
let willQuitApp = false;
function create() {
  // 实例化一个渲染进程
  win = new BrowserWindow({
    width: 600,
    height: 300,
    webPreferences: {
      // 在 webview 页集成 node
      nodeIntegration: true,
      // 禁用上下文隔离
      contextIsolation: false,
      // 在渲染进程中允许使用远程模块
      enableRemoteModule: true,
    },
  });

  win.on("close", (e) => {
    if (willQuitApp) {
      win = null;
    } else {
      e.preventDefault();
      win.hide();
    }
  });

  if (isDev) {
    win.loadURL("http://localhost:3000");
  } else {
    win.loadFile(
      path.resolve(__dirname, "../../renderer/pages/main/index.html")
    );
  }
}

// 控制端主进程向渲染进程发送数据
function send(channel, ...args) {
  win.webContents.send(channel, ...args);
}

function show() {
  win.show();
}

function close() {
  willQuitApp = true;
  win.close();
}

module.exports = { create, send, show, close };
